# coding=utf-8
import logging,time,os
import configparser

class Log():
    def __init__(self):
        # 文件命名
        self.log_path = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))),"logs")
        self.logname = os.path.join(self.log_path,'%s.log'%time.strftime('%Y_%m_%d'))
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        # 日志输出格式
        self.formatter = logging.Formatter('[%(asctime)s]-%(filename)s-%(levelname)s:%(message)s')

    def __console(self,level,message):
        # 创建一个FileHandler用于写到本地
        fh = logging.FileHandler(self.logname,'a','utf-8')
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(self.formatter)
        self.logger.addHandler(fh)
        # 创建一个StreamHandler用于写到控制台
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        sh.setFormatter(self.formatter)
        self.logger.addHandler(sh)
        if level=='info':
            self.logger.info(message)
        elif level=='debug':
            self.logger.debug(message)
        elif level=='waring':
            self.logger.warning(message)
        elif level=='error':
            self.logger.error(message)

        self.logger.removeHandler(fh) # 移除重复的
        self.logger.removeHandler(sh)

    def debug(self,message):
        self.__console('debug',message)

    def info(self,message):
        self.__console('info',message)

    def waring(self,message):
        self.__console('waring',message)

    def error(self,message):
        self.__console('error',message)

if __name__ == '__main__':
    log = Log()
    log.info("----测试开始------")
    log.error("--出错了-----")